package android.gpsmessenger;

import java.io.*;
import java.util.*;

//import android.os.Environment;
import android.util.Xml;
import android.app.Activity;

import org.xmlpull.v1.XmlSerializer;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;

public class TripManager
{
	private String _xmlFile;
	private Activity _activity;
	
	public TripManager(Activity activity)
	{
		_activity = activity;
		_xmlFile = "/trips.xml";
	    //_xmlFile = Environment.getExternalStorageDirectory().getPath() + "/trips.xml";
	}
	
	public TripManager()
	{
		_activity = new Activity();
		_xmlFile = "/trips.xml";
		//_xmlFile = Environment.getExternalStorageDirectory().getPath() + "/trips.xml";
	}
	public void setActivity(Activity activity)
	{
		_activity = activity;
	}
	
	public Location getCurrentLocation()
	{
		return new Location();
	}
	
	public String getSOSLocationMessage()
	{
		return new LocationMessageFactory().createSOSLocationMessage(getCurrentLocation());
	}
	
	public String getLocationMessage()
	{
		return new LocationMessageFactory().createLocationMessage("www.googlemaps.com");
	}
	
	public TripList load() 
	{
		String tripName;
		TripList trips = null ;//= new TripList();
		XmlPullParser parser = Xml.newPullParser();
		try 
		{
			File myFile = new File(_activity.getFilesDir().getAbsolutePath() + _xmlFile);

			InputStream in = new FileInputStream(myFile);
			
			parser.setInput(in, null);
			int eventType = parser.getEventType();
			boolean done = false;
			Trip currentTrip =null;// new Trip();
			Contact newContact;// = new Contact();  
			Location newLocation;// = new Location();
			String id, name, phone, email, longitude, latitude;
			
			while (eventType != XmlPullParser.END_DOCUMENT && !done)
			{
				String tagName = null;
				switch (eventType)
				{
					case XmlPullParser.START_DOCUMENT:
						trips = new TripList();
						break;
					case XmlPullParser.START_TAG:
						tagName = parser.getName();
						if (tagName.equalsIgnoreCase("trip"))
						{
							tripName = parser.getAttributeValue(null, "name");
							currentTrip = new Trip(tripName);
							//currentTrip.setName(tripName);
						}
						else if (currentTrip != null)
						{
							if (tagName.equalsIgnoreCase("contact"))
							{
								id = parser.getAttributeValue(null, "id");
								name = parser.getAttributeValue(null, "name");
					            phone = parser.getAttributeValue(null, "phone");
					            email = parser.getAttributeValue(null, "email");
					            
					            newContact = new Contact(name, phone, email, id);
								currentTrip.addContact(newContact); 									
							}
							else if (tagName.equalsIgnoreCase("location"))
							{
								longitude = parser.getAttributeValue(null, "longitude");
								latitude = parser.getAttributeValue(null, "latitude");
								
								newLocation = new Location(Integer.parseInt(longitude), Integer.parseInt(latitude));
								currentTrip.addLocation(newLocation);
							}
						}
						break;
					case XmlPullParser.END_TAG:
						tagName = parser.getName();
						if (tagName.equalsIgnoreCase("trip") && currentTrip != null)
							trips.addTrip(currentTrip.getName(), currentTrip);
						else if (tagName.equalsIgnoreCase("trips"))
							done = true;
						break;
				}

				eventType = parser.next();
			}
		}
		catch (IOException e) {e.printStackTrace();} 
		catch (XmlPullParserException e) {e.printStackTrace();}   
		
		return trips;
}	
	
	public void save(TripList trips)
	{
		try
		{ 	
			String str = writeXML(trips);
			File myFile = new File(_activity.getFilesDir().getAbsolutePath() + _xmlFile);
			
            myFile.createNewFile();
            FileOutputStream fOut = new FileOutputStream(myFile);
            OutputStreamWriter myOutWriter =  new OutputStreamWriter(fOut);
            myOutWriter.append(str);
            myOutWriter.close();
            fOut.close();
		}
		catch(IOException ioe) {ioe.printStackTrace();}		
	}
	
 	private String writeXML(TripList trips)
 	{
 	    XmlSerializer serializer = Xml.newSerializer();
 	    StringWriter writer = new StringWriter();
 	    Trip currentTrip = null;
 	    try {
 	        serializer.setOutput(writer);
 	        serializer.startDocument("UTF-8", true);
 	        serializer.startTag("", "trips");
 	        
	        Iterator<String> tripIterator = trips.iterator();
 	        while(tripIterator.hasNext())
 	        {
 	        	String tripName = (String) tripIterator.next(); 
 	        	currentTrip = trips.getTrip(tripName);
 	        	
 		        serializer.startTag("", "trip");
 	 	        serializer.attribute("", "name", tripName);
 	 	        serializer.startTag("", "contacts");
 	 	        
 	 	        Contact sosContact = currentTrip.getContacts().getSOSContact();
 	 	        serializer.startTag("", "contact");
 	 	        serializer.attribute("", "id", sosContact.getID());
 	 	        serializer.attribute("", "name", sosContact.getName());
 	 	        serializer.attribute("", "phone", sosContact.getPhone());
 	 	        serializer.attribute("", "email", sosContact.getEmail());
 	 	        serializer.endTag("", "contact"); 	 	        
 	 	        
 	 	        Iterator<Contact> helpContactIterator = currentTrip.getContacts().helpContactsIterator();
 	 	        while(helpContactIterator.hasNext())
 	 	        {
 	 	        	Contact hc = (Contact) helpContactIterator.next(); 	
 	 	        	 	 	        
 	 	        	serializer.startTag("", "contact");
 	 	        	serializer.attribute("", "id", hc.getID());
 	 	        	serializer.attribute("", "name", hc.getName());
 	 	        	serializer.attribute("", "phone", hc.getPhone());
 	 	        	serializer.attribute("", "email", hc.getEmail()); 
 	 	        	serializer.endTag("", "contact");
 		        }
 	 	        
 	 	        Iterator<Contact> friendContactIterator = currentTrip.getContacts().friendContactsIterator();
 	 	        while(friendContactIterator.hasNext())
 	 	        {
 	 	        	Contact fc = (Contact) friendContactIterator.next(); 	
 	 	        	 	 	        
 	 	        	serializer.startTag("", "contact");
 	 	        	serializer.attribute("", "id", fc.getID());
 	 	        	serializer.attribute("", "name", fc.getName());
 	 	        	serializer.attribute("", "phone", fc.getPhone());
 	 	        	serializer.attribute("", "email", fc.getEmail()); 
 	 	        	serializer.endTag("", "contact");
 		        }
 	 	        
 	 	        serializer.endTag("", "contacts");
 	 	        
 	 	        serializer.startTag("", "locations");
 		        Iterator<Location> locationIterator = currentTrip.getLocations().iterator();
 	 	        while(locationIterator.hasNext())
 	 	        {
 	 	        	Location l = (Location) locationIterator.next(); 	
 	 	        	 	 	        
 	 	        	serializer.startTag("", "location");
 	 	        	serializer.attribute("", "longitude", Double.toString(l.getLongitude()));
 	 	        	serializer.attribute("", "latitude", Double.toString(l.getLatitude()));
 	 	        	serializer.endTag("", "location");
 		        } 	 	        
 	 	        serializer.endTag("", "locations");
 	 	      
 		        serializer.endTag("", "trip"); 	 	        
 	        }
 	        
 	        serializer.endTag("", "trips");
 	        serializer.endDocument();
 	        return writer.toString();
 	    } 
 	    catch (Exception e) {throw new RuntimeException(e);} 
 	}		 	
}

